package com.sanqing.iframe;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.swing.JButton;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import com.sanqing.dao.Dao;
import com.sanqing.iframe.BookSearchFrame.TableListener;
import com.sanqing.model.BookInfo;
import com.sanqing.model.Borrow;
import com.sanqing.model.Item;
import com.sanqing.model.MapPz;

public class GiveBackFrame extends JInternalFrame {
	private int Number;
	private final BorderLayout borderLayout;
	private final BorderLayout borderLayout_1;
	private final JScrollPane scrollPane;
	private final JPanel mainPanel;
	private final JPanel giveBackSearchPanel;
	private final JPanel giveBackPanel;
	private final GridLayout gridLayout;
	private final GridLayout gridLayout1;
	private final JButton giveBackButton;
	private final JButton closeButton;
	private int getSelectTableRow=-1;
	private  String giveBackISBN;
	private JTable table;
    private Object[][] results;
    private Object[][] Results;
    private String[] columnNames;
    
	private Map<String,Boolean>mapISBN=new HashMap<>();
	
	
	private Object[][] getFileStates(List list) {
	       String[] columnNames = {"图书编号", "图书类别", "图书名称", "作者", "译者", "出版商", "出版日期", "价格","借阅日期", "归还日期"};
	       Object[][] results = new Object[list.size()][columnNames.length];
	       for (int i = 0; i < list.size(); i++) {
	           BookInfo bookinfo = (BookInfo) list.get(i);
	           List list1=Dao.selectBorrow("select * from tb_borrow where bookISBN='"+bookinfo.getISBN()+"'and readerISBN='"+BookLoginIFrame.getOperator().getISBN()+"'");
	    	   Borrow borrow=(Borrow)list1.get(0);
	           results[i][0] = bookinfo.getISBN();
	           // 获取图书类型名称
	           Integer typeId = bookinfo.getTypeid();
	           //System.out.println(typeId);
	           String bookTypeName = MapPz.getIdToName().get(typeId);
	           //System.out.println(bookTypeName);
	           results[i][1] = bookTypeName;
	           results[i][2] = bookinfo.getBookname();
	           results[i][3] = bookinfo.getWriter();
	           results[i][4] = bookinfo.getTranslator();
	           results[i][5] = bookinfo.getPublisher();
	           results[i][6] = bookinfo.getDate();
	           results[i][7] = bookinfo.getPrice();
	           results[i][8] = borrow.getBorrowDate();
	           results[i][9] = borrow.getBackDate();
	           
	       }
	       return results;
	   }
	public GiveBackFrame() {
       super();
       //Results=new Object[1][];
       borderLayout = new BorderLayout();
       getContentPane().setLayout(borderLayout);
       setIconifiable(true);
       setClosable(true);
       setTitle("归还图书");
       setBounds(100, 100, 593, 406);
       mainPanel = new JPanel();
       borderLayout_1 = new BorderLayout();
       borderLayout_1.setVgap(5);
       mainPanel.setLayout(borderLayout_1);
       mainPanel.setBorder(new EmptyBorder(5, 10, 5, 10));
       getContentPane().add(mainPanel);
       scrollPane = new JScrollPane();
       mainPanel.add(scrollPane);
       
       //
       giveBackSearchPanel=new JPanel();
       mainPanel.add(giveBackSearchPanel,BorderLayout.NORTH);
       gridLayout=new GridLayout(1,4);
       gridLayout.setHgap(0);
       giveBackSearchPanel.setLayout(gridLayout);

       giveBackPanel = new JPanel();
       mainPanel.add(giveBackPanel,BorderLayout.SOUTH);
       gridLayout1=new GridLayout(1,2);
       giveBackPanel.setLayout(gridLayout1);
       giveBackButton=new JButton();
       closeButton =new JButton();
       giveBackButton.setText("归还");
       closeButton.setText("关闭");
       giveBackButton.addActionListener(new giveBackButtonAction());
       closeButton.addActionListener(new colseActionListener() {//注册监听器
	       public void actionPerformed(final ActionEvent e) {
	           doDefaultCloseAction();//关闭窗体
	       }
	   });
       giveBackPanel.add(giveBackButton);
       giveBackPanel.add(closeButton);
       Results=getFileStates(Dao.selectBookinfo("select * from tb_bookinfo where ISBN IN(select bookISBN from tb_borrow where readerISBN='"+BookLoginIFrame.getOperator().getISBN()+"' and isback=0)"));
       Number=Results.length;
       for(int i=0;i<Number;i++)
       {
    	   mapISBN.put((String)Results[i][0], true);
       }
       tableR();
	}
	
	
	private class giveBackButtonAction implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			// TODO Auto-generated method stub
			if(Number==0)
            {
            	JOptionPane.showMessageDialog(null,"表格中尚未添加任何数据","提示",JOptionPane.ERROR_MESSAGE);
            }
			else if(getSelectTableRow!=-1)
			{
				DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");
            	String backDate=dateTimeFormatter.format(LocalDate.now());
            	String se=Dao.selectReserveReaderISBN("select * from tb_reserve where bookISBN='"+(String)Results[getSelectTableRow][0]+"' and reserveDate IS NULL LIMIT 1");
            	Dao.InsertBorrow("update tb_reserve set reserveDate='"+backDate+"' where readerISBN ='"+se+"' and bookISBN='"+(String)Results[getSelectTableRow][0]+"'");
            	Dao.InsertBorrow("update tb_borrow set isback = 1,backDate= '"+backDate+"' where readerISBN='"+BookLoginIFrame.getOperator().getISBN()+"' and bookISBN='"+(String)Results[getSelectTableRow][0]+"'");
            	deleteTableRecord();
            	JOptionPane.showMessageDialog(null,"成功归还","提示",JOptionPane.PLAIN_MESSAGE);
            	//giveBackText.setText("请输入要借阅书的ISBN");
			}
			else
			{
				
				DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd");
            	String backDate=dateTimeFormatter.format(LocalDate.now());
            	for(int i=0;i<Number;i++)
            	{
            		Dao.InsertBorrow("update tb_borrow set isback = 1,backDate= '"+backDate+"' where readerISBN='"+BookLoginIFrame.getOperator().getISBN()+"' and bookISBN='"+(String)Results[i][0]+"'");
            		String se=Dao.selectReserveReaderISBN("select * from tb_reserve where bookISBN='"+(String)Results[i][0]+"' and reserveDate IS NULL LIMIT 1");
                	Dao.InsertBorrow("update tb_reserve set reserveDate='"+backDate+"' where readerISBN ='"+se+"' and bookISBN='"+(String)Results[i][0]+"'");
            	}
            	mapISBN=new HashMap<>();
            	Results=new Object[0][0];
            	results=new Object[0][0];
            	tableE();
            	Number=0;
            	JOptionPane.showMessageDialog(null,"图书成功归还","提示",JOptionPane.PLAIN_MESSAGE);
            //	giveBackText.setText("请输入要借阅书的ISBN");
            	if(isHaveBorrowBook(BookLoginIFrame.getOperator().getIndentityCard()))
            	{
            		JOptionPane.showMessageDialog(null,"没有要归还的图书","提示",JOptionPane.ERROR_MESSAGE);
           			doDefaultCloseAction();
            	}
			}
		}
		
	}
	private class colseActionListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			doDefaultCloseAction();//关闭窗体
		}
		
	}
	
	private class deleteButtonAction implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			// TODO Auto-generated method stub
			deleteTableRecord();
		}
		
	}
	
	
	
	private class TableListener implements MouseListener{

		@Override
		public void mouseClicked(MouseEvent arg0) {
			// TODO Auto-generated method stub
			getSelectTableRow=table.getSelectedRow();
		}

		@Override
		public void mouseEntered(MouseEvent arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void mouseExited(MouseEvent arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void mousePressed(MouseEvent arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void mouseReleased(MouseEvent arg0) {
			// TODO Auto-generated method stub
			
		}
		
	}
	private Object[][] addResults(){
		Object[][] Results;
		Number++;
		Results=new Object[Number][];
		for(int i=0;i<Number-1;i++)
			Results[i]=this.Results[i];
		Results[Number-1]=results[0];
		return Results;
	}
	private void tableR()//更新表
    {
		columnNames =new String[] {"图书编号", "图书类别", "图书名称", "作者", "译者", "出版商", "出版日期", "价格","借阅日期","归还日期"}; // 正确声明
		 table = new JTable(Results, columnNames) {
             @Override
             public boolean isCellEditable(int row, int column) {
                 return false; // 所有单元格都不可编辑
             }
         };
	    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
	    scrollPane.setViewportView(table);
	    table.addMouseListener(new TableListener());
    }
    private void tableE()//清空表的内容
    {
    	String[] columnNames =new String[0] ; // 正确声明
    	 table = new JTable(Results, columnNames) {
             @Override
             public boolean isCellEditable(int row, int column) {
                 return false; // 所有单元格都不可编辑
             }
         };
	    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
	    scrollPane.setViewportView(table);
	    table.addMouseListener(new TableListener());
    }
    private static boolean isHaveBorrowBook(String username)
    {
    	int haveBorrowBook=Dao.selectBorrow("select * from tb_borrow where readerISBN='"+username+"'and isback=0").size();
    	if(haveBorrowBook!=0) return false;
    	return true;
    }
    private void deleteTableRecord()
    {
    	if(getSelectTableRow!=-1)
		{
    		Object[][] results=new Object[Number-1][];
			mapISBN.remove((String)Results[getSelectTableRow][0]);
			for(int i=0;i<getSelectTableRow;i++) results[i]=Results[i];
			for(int i=getSelectTableRow+1;i<Number;i++)
			{
				results[i-1]=Results[i];
			}
			Results=results;
			Number--;
			getSelectTableRow=-1;
			if(Number!=0)tableR();
			else 
			tableE();
			
		}
		else
		{
			JOptionPane.showMessageDialog(null,"未选择表中的数据或者表中没有数据","提示",JOptionPane.ERROR_MESSAGE);
		}

    }
}
